package wzc.design_pattern.construction.proxy;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 那和不是个啥
 * @Date 2025/7/20
 * @Description
 */

public class DatabaseProxy implements Database {
    private RealDatabase realDatabase;
    private final Map<String, String> cache = new HashMap<>();
    @Override
    public String query(String sql) {
        if (cache.containsKey(sql)) {
            System.out.println("从缓存中返回结果：" + cache.get(sql));
            return cache.get(sql);
        }

        // 否则查询数据库，并存入缓存
        if (realDatabase == null) {
            realDatabase = new RealDatabase();
        }
        String result = realDatabase.query(sql);
        cache.put(sql, result);

        return result;
    }
}
